/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package modules.enderecamento.models.dao;

/**
 *
 * @author Clezio
 */
import java.util.ArrayList;
import java.util.List;
import modules.enderecamento.models.dto.Cargo;
import modules.enderecamento.util.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;
   
 public class CargoDAO{  
     
     private SessionFactory sessionFactory;
     
     public CargoDAO() throws Exception{
         sessionFactory = HibernateUtil.getSessionFactory();
     }
       
     public void save(Cargo cargo) throws ConstraintViolationException, Exception{
         Session session = sessionFactory.openSession();
         Transaction tx = session.beginTransaction();
         try{
             if(cargo.getId() > 0){
                session.update(cargo);
             }else{
                session.save(cargo);
             }
         }catch(ConstraintViolationException e){
             throw e;
         }catch(Exception e){
             throw e;
         }
         session.flush();
         tx.commit();
         session.close();  
     }  
       
     public java.util.List<Cargo> getList(String condicao) throws Exception{
         Session session = sessionFactory.openSession();
         Query query = session.createQuery(condicao);
         List clientes = new ArrayList(query.list());
         session.flush();  
         session.close();  
         return clientes;
     }  
       
     public Cargo retrieve(Integer pk) throws Exception{
         Session session = sessionFactory.openSession();
         Cargo cliente = (Cargo)session.load(Cargo.class, pk);
         Cargo clienteDTO = mountDto(cliente);
         session.flush();
         session.close();  
         return clienteDTO;
     }  
       
     public void delete(Cargo cargo) throws Exception{
         Session session = sessionFactory.openSession();
         Transaction tx = session.beginTransaction();
         session.delete(cargo);
         session.flush();
         tx.commit();
         session.close();  
     }

    public Cargo mountDto(Cargo cargo) {
        Cargo clienteDTO = new Cargo();
        clienteDTO.setId(cargo.getId());
        clienteDTO.setNome(cargo.getNome());
        clienteDTO.setDescricao(cargo.getDescricao());
        clienteDTO.setAtivo(cargo.isAtivo());
        return clienteDTO;
    }
 }